package com.stackfarm.fvservice.security.Realms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stackfarm.fvcommon.exception.UnhandledException;
import com.stackfarm.fvcommon.pojo.Users;
import com.stackfarm.fvcommon.utils.JwtUtil;
import com.stackfarm.fvservice.mapper.UsersMapper;
import com.stackfarm.fvservice.security.JwtToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
public class UserRealm extends AuthorizingRealm {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 必须重写的方法，如果缺少引起shiro错误
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     *授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     *认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        return new SimpleAuthenticationInfo(verifyToken(token), token, this.getName());
    }

    private Users verifyToken(String token) {
        String username;
        try {
            username = JwtUtil.getUserName(token);
        } catch (UnhandledException e) {
            throw new ExpiredCredentialsException(e.getMsg());
        }
        Users currentUser = usersMapper.selectOne(new QueryWrapper<Users>().eq("username",username));
        if (currentUser == null) {
            throw new UnknownAccountException("未注册用户");
        }
        return currentUser;
    }
}
